package com.github.wisdom.common.github.modules.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.toolkit.MapUtils;
import com.baomidou.mybatisplus.toolkit.StringUtils;

public class EntityWrapperHandle<T> extends EntityWrapper<T> {

	private static final String[] ignoreKey = { "t", "time", "page", "limit" };

	public static final char UNDERLINE = '_';

	private static final long serialVersionUID = 4490148164124780458L;

	public EntityWrapperHandle() {
		super();
	}

	public EntityWrapperHandle(Map<String, Object> params) {
		super();
		Map<String, Object> map = new HashMap<String, Object>(params);
		this.allEq(map);
	}

	public EntityWrapperHandle(String column, String value, SqlLike type) {
		super();
		this.like(column, value, type);
	}

	@Override
	public Wrapper<T> allEq(Map<String, Object> map) {
		for (String key : ignoreKey) {
			map.remove(key);
		}
		return this.allEq(true, map);
	}

	@Override
	public Wrapper<T> like(String column, String value, SqlLike type) {
		if (StringUtils.isNotEmpty(column) && StringUtils.isNotEmpty(value)) {
			return super.like(true, isUnderlineCharAt(column), value, type);
		}
		return this;
	}

	@Override
	public Wrapper<T> allEq(boolean condition, Map<String, Object> params) {
		if (condition && MapUtils.isNotEmpty(params)) {
			Iterator<?> iterator = params.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iterator.next();
				Object value = entry.getValue();
				if (StringUtils.checkValNotNull(value)) {
					sql.WHERE(
							formatSql(String.format("%s = {0}", isUnderlineCharAt(entry.getKey())), entry.getValue()));
				}
			}
		}
		return this;
	}

	public static String propertyToUnderline(String key) {
		if (key == null || "".equals(key.trim())) {
			return "";
		}
		int len = key.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = key.charAt(i);
			if (Character.isUpperCase(c)) {
				sb.append(UNDERLINE);
				sb.append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	private static String isUnderlineCharAt(String key) {
		String underlineStr = String.valueOf(UNDERLINE);
		boolean status = key.contains(underlineStr);
		if (status) {
			return key.toUpperCase();
		} else {
			return propertyToUnderline(key);
		}
	}

}
